<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    #container {
      width: 100%;
      height: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
    }

    canvas {
      border: 1px solid black;
      height: 400px;
      width: 400px;

    }
  </style>
</head>

<body>

  <div id="container">
    <canvas id="myCanvas"></canvas>
  </div>
  <script>
    try {
      const canvas = document.getElementById('myCanvas');
      if (!canvas) throw new Error('Canvas 元素未找到');

      const ctx = canvas.getContext('2d');
      if (!ctx) throw new Error('无法获取 2D 上下文');

      // 定义正方形的属性
      const square = {
        x: 0, // 左上角横坐标
        y: 0, // 左上角纵坐标
        width: 400, // 正方形宽度
        height: 400 // 正方形高度
      };

      // 绘制红色实心正方形
      ctx.fillStyle = 'rgba(255, 0, 0, 0.5)';
      // 绘制实心正方形  square是上面定义的正方形对象
      ctx.fillRect(square.x, square.y, square.width, square.height);

      // // 绘制蓝色空心正方形（边框）
      // ctx.strokeStyle = 'blue';
      // ctx.lineWidth = 5;
      // ctx.strokeRect(square.x, square.y, square.width, square.height);
    } catch (error) {
      console.error('绘图时出错:', error);
    }
  </script>
</body>

</html>